﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BaseData.UI;

namespace Admin.Tax
{
    public partial class Backup : BaseCommon.BasePage
    {
        protected static object locker = new object();
        protected string dbName = PageContext.GetConfig("DbName");

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HasPower())
            {
                Jscript.AlertAndGoBack("您权限不足，不能操作");
                return;
            }
            string action = PageContext.GetRequest("action");
            if (!string.IsNullOrEmpty(action))
            {
                lock (locker)
                {
                    BackupDB();
                }
            }
        }

        protected void BackupDB()
        {
            bool isSuccess = true;
            string filePath = PageContext.GetConfig("FilePath") + "Backup\\LNHouse" + DateTime.Now.ToString("yyyyMMddHHmm") + ".bak";
            string message = string.Empty;
            try
            {
                //文件夹不存在即创建
                FileInfo fi = new FileInfo(filePath);
                if (!System.IO.Directory.Exists(fi.Directory.FullName))
                {
                    System.IO.Directory.CreateDirectory(fi.Directory.FullName);
                }
                isSuccess = BaseData.DataConfig.Backup(BaseData.BusinessType.DBAdmin, filePath, dbName);
            }
            catch (Exception e)
            {
                isSuccess = false;
                message = "备份数据库出错，出错信息" + e.Message;
            }
            if (isSuccess)
            {
                FileInfo fileInfo = new FileInfo(filePath);
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.AddHeader("Content-Transfer-Encoding", "binary");
                Response.ContentType = "application/octet-stream";
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                Response.WriteFile(fileInfo.FullName);
                Response.Flush();
                Response.End();
            }
            else
            {
                Jscript.AlertAndRedirect(message, "Backup.aspx");
            }
        }
    }
}